import React from 'react';
import PropTypes from 'prop-types';
import {Button, Form, Row, Col, Divider, Table} from 'antd';
import {FORM_OPTIONS, FORM_ROW_OPTIONS, PAGINATION_OPTIONS, PAGE, COMMON_TABLE_QUERY_FAIL_TEXT, COMMON_TABLE_EMPTY_TEXT, TABLE} from '../constants';
import {repairType, claimStatus} from '../Enum';
import TextInput from 'Shared/components/TextInput';
import WrappedSelect from '../common/WrappedSelect';
import DateRangePicker from 'Shared/components/DateRangePicker';
import TagSelect from 'Shared/components/TagSelect';
import {conventSorter} from './utils';
import {injectIntl, language} from './intl';
import styles from './style.css';
import {getSubClaimHistoryList} from './api';
import moment from 'moment';
import HistoryDetailPanel from './HistoryDetailPanel';
const FormItem = Form.Item;

const repairTypeList = repairType.toList(language);
const claimStatusList = claimStatus.toList(language);
class HistoryQueryPanel extends React.PureComponent {
    state = {
        code: '',
        repairCode: '',
        causePartCode: '',
        causePartName: '',
        vin: '',
        status: [],
        repairType: undefined,
        createTime: undefined,
        pageIndex: PAGE.index,
        pageSize: PAGE.smallSize,
        isFetching: false,
        data: {},
        message: '',
        currentCondition: {}
    }
    componentDidMount() {
        if(this.props.vehicleQueryParamObj)
            this.setState({
                vin: this.props.vehicleQueryParamObj.vin
            });
    }
    handleTableChange = (pagination, filters, sorter) => {
        const oldCondition = {...this.state.currentCondition};
        if(pagination.current - 1 === oldCondition.pageIndex && pagination.pageSize === oldCondition.pageSize) {
            const sortOptions = conventSorter(sorter);
            const condition = Object.assign({}, oldCondition, sortOptions, {
                pageIndex: PAGE.index
            });
            this.onQuery(condition);
            this.setState({
                sortField: sortOptions.sortField,
                isDesc: sortOptions.isDesc
            });
        }
    }
    handleFilterPressEnter = (value, name) => {
        this.setState({[name]: value}, this.onClickSearchBtn);
    }
    onQuery = condition => {
        this.setState({isFetching: true});
        const conventDate = (condition = {}) => {
            const {createTime, ...others} = condition;
            if(!createTime || createTime.length === 0) return condition;
            return {
                ...others,
                beginCreateTime: moment(createTime[0]).toISOString(),
                endCreateTime: moment(createTime[1]).toISOString(),
            };
        };
        getSubClaimHistoryList(conventDate(condition))
            .then(res => {
                if(res.ok)
                    this.setState({
                        isFetching: false,
                        message: '',
                        data: res.data,
                        currentCondition: condition
                    });
                else
                    this.setState({
                        isFetching: false,
                        data: [],
                        message: res.message
                    });
            });
    }

    onClickSearchBtn = () => {
        const condition = {
            code: this.state.code,
            repairCode: this.state.repairCode,
            causePartCode: this.state.causePartCode,
            causePartName: this.state.causePartName,
            vin: this.state.vin,
            status: this.state.status,
            repairType: this.state.repairType,
            pageIndex: PAGE.index,
            pageSize: this.state.pageSize,
            sortField: this.state.sortField,
            isDesc: this.state.isDesc
        };
        this.onQuery(condition);
    }

    onPageIndexChange = current => {
        const condition = {...this.state.currentCondition};
        condition.pageIndex = current - 1;
        this.onQuery(condition);
    }

    onPageSizeChange = (current, pageSize) => {
        const condition = {...this.state.currentCondition};
        condition.pageIndex = PAGE.index;
        condition.pageSize = pageSize;
        this.onQuery(condition);
        this.setState({
            pageSize
        });
    }

    onChange = (value, name) => {
        this.setState({[name]: value});
    }
    onClickReset = () => {
        this.setState({
            code: '',
            repairCode: '',
            causePartCode: '',
            causePartName: '',
            vin: '',
            status: [],
            repairType: undefined,
            createTime: undefined,
            id: '',
            showDetail: false
        });
    }
    onChangeDetail = e => {
        this.setState({
            id: e.target.id,
            showDetail: true
        });
    }
    onCloseHistoryDetail = () => {
        this.setState({
            id: '',
            showDetail: false
        });
    }
    render() {
        const {formatMessage} = this.props.intl;
        const {isFetching, data} = this.state;
        const {pageIndex, pageSize} = this.state.currentCondition;
        const columns = [
            {
                title: formatMessage({
                    id: 'historyQueryPanel.column.code',
                    defaultMessage: '索赔单编号'
                }),
                dataIndex: 'code',
                width: '100px',
                sorter: true,
                render: (text, record) => <Button className={styles.btnh} type="link" id={record.id} onClick={this.onChangeDetail} >{text}</Button>
            }, {
                title: formatMessage({
                    id: 'historyQueryPanel.column.repairCode',
                    defaultMessage: '委托书编号'
                }),
                dataIndex: 'repairCode',
            }, {
                title: formatMessage({
                    id: 'historyQueryPanel.column.causePartCode',
                    defaultMessage: '主损件编号'
                }),
                dataIndex: 'causePartCode',
            }, {
                title: formatMessage({
                    id: 'historyQueryPanel.column.causePartName',
                    defaultMessage: '主损件名称'
                }),
                dataIndex: 'causePartName',
            }, {
                title: formatMessage({
                    id: 'historyQueryPanel.column.vin',
                    defaultMessage: 'VIN'
                }),
                dataIndex: 'vin',
            }, {
                title: formatMessage({
                    id: 'historyQueryPanel.column.status',
                    defaultMessage: '状态'
                }),
                dataIndex: 'status',
            }, {
                title: formatMessage({
                    id: 'historyQueryPanel.column.repairType',
                    defaultMessage: '索赔类型'
                }),
                dataIndex: 'repairType',
            }, {
                title: formatMessage({
                    id: 'historyQueryPanel.column.productionDate',
                    defaultMessage: '生产日期'
                }),
                dataIndex: 'productionDate',
            }, {
                title: formatMessage({
                    id: 'historyQueryPanel.column.saleDate',
                    defaultMessage: '实销日期'
                }),
                dataIndex: 'saleDate',
            }, {
                title: formatMessage({
                    id: 'historyQueryPanel.column.engineCode',
                    defaultMessage: '发动机号'
                }),
                dataIndex: 'engineCode',
            }, {
                title: formatMessage({
                    id: 'historyQueryPanel.column.customerName',
                    defaultMessage: '客户姓名'
                }),
                dataIndex: 'customerName',
            }, {
                title: formatMessage({
                    id: 'historyQueryPanel.column.cellPhoneNumber',
                    defaultMessage: '客户电话'
                }),
                dataIndex: 'cellPhoneNumber',
            }, {
                title: formatMessage({
                    id: 'historyQueryPanel.column.contactName',
                    defaultMessage: '送修人姓名'
                }),
                dataIndex: 'contactName',
            }, {
                title: formatMessage({
                    id: 'historyQueryPanel.column.contactNumber',
                    defaultMessage: '送修人电话'
                }),
                dataIndex: 'contactNumber',
            }, {
                title: formatMessage({
                    id: 'historyQueryPanel.column.totalFee',
                    defaultMessage: '费用合计'
                }),
                dataIndex: 'totalFee',
            }, {
                title: formatMessage({
                    id: 'historyQueryPanel.column.laborFee',
                    defaultMessage: '工时费'
                }),
                dataIndex: 'laborFee',
            }, {
                title: formatMessage({
                    id: 'historyQueryPanel.column.materialFee',
                    defaultMessage: '材料费'
                }),
                dataIndex: 'materialFee',
            }, {
                title: formatMessage({
                    id: 'historyQueryPanel.column.mgmtFee',
                    defaultMessage: '管理费'
                }),
                dataIndex: 'mgmtFee',
            }, {
                title: formatMessage({
                    id: 'historyQueryPanel.column.assistantFee',
                    defaultMessage: '辅料费'
                }),
                dataIndex: 'assistantFee',
            }, {
                title: formatMessage({
                    id: 'historyQueryPanel.column.createTime',
                    defaultMessage: '创建时间'
                }),
                dataIndex: 'createTime',
            }, {
                title: formatMessage({
                    id: 'historyQueryPanel.column.submitTime',
                    defaultMessage: '提交时间'
                }),
                dataIndex: 'submitTime',
            }
        ];
        const pagination = {
            total: data.totalElements,
            current: pageIndex + 1,
            pageSize,
            onShowSizeChange: this.onPageSizeChange,
            onChange: this.onPageIndexChange,
            ...PAGINATION_OPTIONS
        };
        const locale = {
            emptyText: this.props.errorMessage ? COMMON_TABLE_QUERY_FAIL_TEXT : COMMON_TABLE_EMPTY_TEXT
        };
        return (
            <div>
                <Form className="form-standard">
                    <Row>
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'historyQueryPanel.form.code',
                                    defaultMessage: '索赔单号'
                                })}
                                {...FORM_OPTIONS.item}>
                                <TextInput
                                    name="code"
                                    value={this.state.code}
                                    onPressEnter={this.handleFilterPressEnter}
                                    onBlur={this.onChange} />
                            </FormItem>
                        </Col>
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'historyQueryPanel.form.repairCode',
                                    defaultMessage: '委托书编号'
                                })}
                                {...FORM_OPTIONS.item}>
                                <TextInput
                                    name="repairCode"
                                    value={this.state.causePartCode}
                                    onPressEnter={this.handleFilterPressEnter}
                                    onBlur={this.onChange} />
                            </FormItem>
                        </Col>
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'historyQueryPanel.form.causePartCode',
                                    defaultMessage: '主损件编号'
                                })}
                                {...FORM_OPTIONS.item}>
                                <TextInput
                                    name="causePartCode"
                                    value={this.state.causePartCode}
                                    onPressEnter={this.handleFilterPressEnter}
                                    onBlur={this.onChange} />
                            </FormItem>
                        </Col>
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'historyQueryPanel.form.causePartName',
                                    defaultMessage: '主损件名称'
                                })}
                                {...FORM_OPTIONS.item}>
                                <TextInput
                                    name="causePartName"
                                    value={this.state.causePartName}
                                    onPressEnter={this.handleFilterPressEnter}
                                    onBlur={this.onChange} />
                            </FormItem>
                        </Col>
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'historyQueryPanel.form.vin',
                                    defaultMessage: 'VIN'
                                })}
                                {...FORM_OPTIONS.item}>
                                <TextInput
                                    disabled
                                    name="vin"
                                    value={this.state.vin} />
                            </FormItem>
                        </Col>
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'historyQueryPanel.form.repairType',
                                    defaultMessage: '索赔类型'
                                })}
                                {...FORM_OPTIONS.item}>
                                <WrappedSelect
                                    allowClear
                                    name="repairType"
                                    value={this.state.repairType}
                                    options={repairTypeList}
                                    onChange={this.onChange} />
                            </FormItem>
                        </Col>
                        <Col {...FORM_OPTIONS.col}>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'historyQueryPanel.form.createTime',
                                    defaultMessage: '创建时间'
                                })}
                                {...FORM_OPTIONS.item}>
                                <DateRangePicker name="createTime" value={this.state.createTime}
                                    onChange={this.onChange} />
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col>
                            <FormItem label={this.props.intl.formatMessage({
                                id: 'historyQueryPanel.form.status',
                                defaultMessage: '状态'
                            })} {...FORM_ROW_OPTIONS.item}>
                                <TagSelect
                                    name="status"
                                    value={this.state.status}
                                    options={claimStatusList}
                                    onChange={this.onChange} />
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span={6}>
                            <Button
                                type="primary"
                                loading={isFetching}
                                className={styles.btnMargin}
                                onClick={this.onClickSearchBtn}>
                                {formatMessage({
                                    id: 'historyQueryPanel.btn.query',
                                    defaultMessage: '查询'
                                })}
                            </Button>
                            <Button key="clear" onClick={this.onClickReset}>{formatMessage({
                                id: 'historyQueryPanel.btn.reset',
                                defaultMessage: '重置'
                            })}</Button>
                        </Col>
                    </Row>
                </Form>
                <Divider className={styles.divider}/>
                <Table
                    className="white-space-nowrap"
                    rowKey="id"
                    dataSource={data.content}
                    columns={columns}
                    loading={isFetching}
                    pagination={pagination}
                    onChange={this.handleTableChange}
                    locale={locale}
                    {...TABLE} />
                {
                    this.state.showDetail &&
                    <HistoryDetailPanel
                        id={this.state.id}
                        selectKey={this.state.id}
                        onCancel={this.onCloseHistoryDetail}/>
                }
            </div>
        );
    }
}

HistoryQueryPanel.propTypes = {
    intl: PropTypes.object,
    vehicleQueryParamObj: PropTypes.object,
};

export default injectIntl(HistoryQueryPanel);
